from kubernetes import client, config

# 指定配置文件路径
config.load_kube_config(config_file='/tmp/config')

# 创建 Kubernetes API 客户端
v1 = client.CoreV1Api()

namespaces = ['my-test', 'opx', 'default']  # 命名空间名称列表

# 遍历每个命名空间下的 Service 列表，并输出分隔行和表头
for namespace in namespaces:
    print('-' * 80)
    print(f'Namespace: {namespace}\n')
    print(f'{"NAME":30} {"TYPE":10} {"CLUSTER-IP":20} {"EXTERNAL-IP(S)":20} {"PORT(S)":20} {"AGE":15}')

    service_list = v1.list_namespaced_service(namespace, watch=False)

    # 遍历 Service 列表
    for service in service_list.items:
        # 获取 Cluster IP 和 Node Port
        cluster_ip = service.spec.cluster_ip or ''
        node_port = ''
        if service.spec.type == 'NodePort':
            ports = [f'{port.node_port}/{port.protocol}' for port in service.spec.ports]
            node_port = ', '.join(ports)

        # 获取 External IPs
        external_ips = []
        if service.spec.external_name:
            external_ips.append(service.spec.external_name)
        if service.spec.load_balancer_ip:
            external_ips.append(service.spec.load_balancer_ip)
        if service.spec.load_balancer_source_ranges:
            external_ips.extend(service.spec.load_balancer_source_ranges)
        external_ips = ', '.join(external_ips)

        # 获取年龄
        age = service.metadata.creation_timestamp

        # 打印输出每个 Service 的名称、类型、Cluster IP、External IPs、Ports 和年龄
        print(
            f'{service.metadata.name:30} {service.spec.type:10} {cluster_ip:20} {external_ips:20} {node_port:20} {age:15}')
